import type { LngLat } from 'mapbox-gl';
import { useEffect, useRef, useState } from 'react';
import type { Mapless } from '@/components/MapView';
import { PositionMouse } from '@/components/MapView/Mapless/core/position.mus';
import styles from '../index.module.less';

const PositionMus: React.FC<{
  mapless: Mapless | undefined;
}> = (props) => {
  const { mapless } = props;

  const divRef = useRef<HTMLDivElement>(null);
  const pmusRef = useRef<PositionMouse>(undefined);

  const [position, setPosition] = useState<LngLat | null>(null);
  const [zoom, setZoom] = useState<string | null>(null);

  useEffect(() => {
    if (mapless?.map) {
      pmusRef.current = new PositionMouse(mapless.map);
      pmusRef.current.onPositionChange = (coord: LngLat) => {
        setPosition(coord);
      };
      pmusRef.current.onZoomChange = (_z: number) => {
        setZoom(mapless?.map?.getZoom()?.toFixed(0) || '--');
      };
      setZoom(mapless?.map?.getZoom()?.toFixed(0) || '--');
      pmusRef.current.startMouse();
      // PositionMouse's leaveHandler not effect
      divRef.current?.parentElement?.addEventListener('mouseleave', () => {
        setPosition(null);
      });
    }
    return () => {
      pmusRef.current?.stopMouse();
    };
  }, [mapless]);

  return (
    <div ref={divRef} className={styles.mousepos}>
      {zoom && <span style={{ opacity: 0.5 }}>Z : {zoom}</span>}
      {position && (
        <div style={zoom ? { marginLeft: 12 } : {}}>
          {position.lng.toFixed(6)} , {position.lat.toFixed(6)}
        </div>
      )}
    </div>
  );
};

export default PositionMus;
